package flc.ast.utils;

import android.net.TrafficStats;
import android.os.Handler;

public class NetworkSpeedMonitor {
    private Handler mHandler = new Handler();
    private long mLastRxBytes = 0; // 上次接收的字节数
    private long mLastTxBytes = 0; // 上次发送的字节数
    private long mLastTime = 0;    // 上次记录时间
    private SpeedListener mListener;

    public interface SpeedListener {
        void onSpeedChanged(double downloadSpeedMbps, double uploadSpeedMbps);
    }

    public NetworkSpeedMonitor(SpeedListener listener) {
        mListener = listener;
    }

    /**
     * 开始监控网速
     */
    public void start() {
        mLastRxBytes = TrafficStats.getTotalRxBytes();
        mLastTxBytes = TrafficStats.getTotalTxBytes();
        mLastTime = System.currentTimeMillis();
        mHandler.postDelayed(mRunnable, 1000); // 每隔 1 秒更新一次
    }

    /**
     * 停止监控网速
     */
    public void stop() {
        mHandler.removeCallbacks(mRunnable);
    }

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            // 获取当前接收和发送的字节数
            long currentRxBytes = TrafficStats.getTotalRxBytes();
            long currentTxBytes = TrafficStats.getTotalTxBytes();
            long currentTime = System.currentTimeMillis();

            // 计算下载和上传速度（单位：字节/秒）
            long downloadSpeedBps = (currentRxBytes - mLastRxBytes) * 1000 / (currentTime - mLastTime);
            long uploadSpeedBps = (currentTxBytes - mLastTxBytes) * 1000 / (currentTime - mLastTime);

            // 转换为 Mbps
            double downloadSpeedMbps = (downloadSpeedBps * 8) / 1024.0 / 1024.0;
            double uploadSpeedMbps = (uploadSpeedBps * 8) / 1024.0 / 1024.0;

            // 更新上次记录的值
            mLastRxBytes = currentRxBytes;
            mLastTxBytes = currentTxBytes;
            mLastTime = currentTime;

            // 回调监听器
            if (mListener != null) {
                mListener.onSpeedChanged(downloadSpeedMbps, uploadSpeedMbps);
            }

            // 每隔 1 秒再次执行
            mHandler.postDelayed(this, 1000);
        }
    };
}